// elastic_lib.go
package common

import (
	//"encoding/json"
	"fmt"

	//"log"
	//"sort"
	"strings"
	"time"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/olivere/elastic/v7"
)

var Esclient *elastic.Client

func init() {
	var dberr error
	xEsUri, _ := beego.AppConfig.String("EsUri")
	if xEsUri != "" {
		//Esclient, dberr = elastic.NewClient(elastic.SetURL("http://192.168.x.xx:9203", "http://192.168.xx.xx:9203"))
		EsUri := strings.Split(xEsUri, ",")
		//Esclient, dberr = elastic.NewClient(elastic.SetURL(EsUri...))
		Esclient, dberr = elastic.NewSimpleClient(elastic.SetURL(EsUri...))
		if dberr != nil {
			// Handle error
			//panic(dberr)
			fmt.Println(dberr)
		}
		defer Esclient.Stop()
	}
}

func GetIndex(index string, starttime, endtime int64) []string {
	nowst := time.Now().UnixNano() / 1e6
	HowDaysBefore := (nowst-starttime)/86400000 + 1 //计算多少天以前
	TimesLong := (endtime-starttime)/86400000 + 1   //计算开始到结束的时长
	var endnum int64
	startDate := time.Unix(starttime/1000, 0).Format("2006.01.02")
	endDate := time.Unix(endtime/1000, 0).Format("2006.01.02")
	endnum = HowDaysBefore - TimesLong
	h, _ := time.ParseDuration("-24h") //索引以天为单位
	var i int64
	var indexArry = []string{}
	for i = HowDaysBefore; i >= endnum; i-- {
		d1 := time.Now().Add(time.Duration(i) * h).Format("2006.01.02")
		t1, err := time.Parse("2006.01.02", d1)
		t2, err := time.Parse("2006.01.02", startDate)
		if err == nil && t1.Before(t2) { //循环里的日期在开始时间之前就跳过
			continue
		}
		indexArry = append(indexArry, index+"-"+d1) //当循环中等于结束时间时就结束
		if d1 == endDate {
			break
		}
	}
	return indexArry
}
